<template>
  <div class="homework-container">
    <h1>作业列表</h1>
    
    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }}老师</p>
      <router-link to="/teacher/dashboard">返回Dashboard</router-link>
    </div>

    <div class="teaching-courses" v-if="userProfile.teachingCourses && userProfile.teachingCourses.length > 0">
      <h2>选择班级查看作业</h2>
      <div class="course-selection">
        <div 
          v-for="(course, index) in userProfile.teachingCourses" 
          :key="index" 
          class="course-card"
          :class="{ selected: selectedCourse === course }"
          @click="selectCourse(course)"
        >
          <p>班级: {{ course.className }}</p>
          <p>科目: {{ course.subjectName }}</p>
        </div>
      </div>
    </div>

    <div v-else>
      <p>您还没有授课信息</p>
    </div>

    <!-- 作业列表 -->
    <div v-if="selectedCourse" class="homework-list">
      <div class="list-header">
        <h2>{{ selectedCourse.className }} - {{ selectedCourse.subjectName }} 的作业</h2>
        <button @click="loadHomeworkList" class="refresh-btn">刷新</button>
      </div>
      
      <div v-if="loading" class="loading">
        加载中...
      </div>
      
      <div v-else-if="homeworkList.length > 0" class="homework-items">
        <div 
          v-for="homework in homeworkList" 
          :key="homework.id" 
          class="homework-item"
        >
          <div class="homework-header">
            <h3>{{ homework.title }}</h3>
            <span class="due-date" :class="{ 'expired': isExpired(homework.dueDate) }">
              {{ homework.dueDate ? formatDate(homework.dueDate) : '无截止日期' }}
            </span>
          </div>
          <div class="homework-content">
            <p>{{ homework.content }}</p>
          </div>
          <div class="homework-meta">
            <span>发布时间: {{ formatDate(homework.createdAt) }}</span>
          </div>
          <div class="homework-actions">
            <button @click="viewSubmissions(homework.id)" class="view-submissions-btn">
              查看提交情况
            </button>
          </div>
        </div>
      </div>
      
      <div v-else class="no-homework">
        <p>该班级暂无作业</p>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'ViewHomework',
  setup() {
    const router = useRouter();
    const userProfile = ref({});
    const selectedCourse = ref(null);
    const homeworkList = ref([]);
    const loading = ref(false);
    const errorMessage = ref('');

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
        } else {
          errorMessage.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };

    // 选择课程
    const selectCourse = (course) => {
      selectedCourse.value = course;
      loadHomeworkList();
    };

    // 加载作业列表
    const loadHomeworkList = async () => {
      if (!selectedCourse.value) return;
      
      try {
        loading.value = true;
        errorMessage.value = '';
        
        const response = await fetch(`/homework/list/${selectedCourse.value.classId}`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          homeworkList.value = result.data || [];
        } else {
          errorMessage.value = result.msg || '获取作业列表失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      } finally {
        loading.value = false;
      }
    };

    // 查看提交情况
    const viewSubmissions = (assignmentId) => {
      router.push(`/teacher/homework/submissions/${assignmentId}`);
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };

    // 判断是否过期
    const isExpired = (dateString) => {
      if (!dateString) return false;
      const dueDate = new Date(dateString);
      const now = new Date();
      return dueDate < now;
    };

    onMounted(() => {
      loadUserProfile();
    });

    return {
      userProfile,
      selectedCourse,
      homeworkList,
      loading,
      errorMessage,
      selectCourse,
      loadHomeworkList,
      viewSubmissions,
      formatDate,
      isExpired
    };
  }
};
</script>

<style scoped>
.homework-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.homework-container h1 {
  text-align: center;
  color: #333;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info a {
  color: #409EFF;
  text-decoration: none;
}

.user-info a:hover {
  text-decoration: underline;
}

.teaching-courses h2 {
  color: #333;
}

.course-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.course-card {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 15px;
  cursor: pointer;
  width: calc(50% - 15px);
  box-sizing: border-box;
}

.course-card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.course-card.selected {
  border-color: #409EFF;
  background-color: #e8f4fd;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-header h2 {
  margin: 0;
  color: #333;
}

.refresh-btn {
  padding: 8px 15px;
  background-color: #9E9E9E;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.refresh-btn:hover {
  background-color: #757575;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.homework-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.homework-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
}

.homework-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.homework-header h3 {
  margin: 0;
  color: #333;
}

.due-date {
  font-size: 14px;
  color: #666;
}

.due-date.expired {
  color: #f56c6c;
  font-weight: bold;
}

.homework-content p {
  margin: 0 0 15px 0;
  color: #555;
  line-height: 1.5;
}

.homework-meta {
  font-size: 14px;
  color: #999;
  border-top: 1px solid #eee;
  padding-top: 10px;
  margin-bottom: 15px;
}

.homework-actions {
  display: flex;
  justify-content: flex-end;
}

.view-submissions-btn {
  padding: 8px 16px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.view-submissions-btn:hover {
  background-color: #337ecc;
}

.no-homework {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

@media (max-width: 600px) {
  .course-card {
    width: 100%;
  }
  
  .homework-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .homework-actions {
    justify-content: center;
  }
}
</style>